package xyz.syyrjx.call.load;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import xyz.syyrjx.beaker.annotation.SyyrjxRpcBreaker;
import xyz.syyrjx.call.annotation.SyyrjxRpcCallClient;
import xyz.syyrjx.call.annotation.SyyrjxRpcCallEnable;
import xyz.syyrjx.call.factory.SyyrjxRpcCallClientFactoryBean;


import java.io.IOException;
import java.util.*;

/**
 * @author 大地崩坏苍蝇兽
 * @date 2023/1/22 - 12:06
 */
public class SyyrjxRpcCallLoadAware implements ImportBeanDefinitionRegistrar,
        ResourceLoaderAware, EnvironmentAware, ApplicationContextAware {

    private final static Logger LOGGER = LoggerFactory.getLogger(SyyrjxRpcCallLoadAware.class);

    private ResourceLoader resourceLoader;

    private Environment environment;


    @Override
    public void setEnvironment(Environment environment) {
        LOGGER.debug("载入环境");
        this.environment = environment;
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        LOGGER.debug("载入资源加载器");
        try {
            LOGGER.debug("加载路径为" + resourceLoader.getResource("").getURI());
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata
            , BeanDefinitionRegistry registry) {
        LOGGER.debug("进行接口声明式调用创建");

        ClassPathScanningCandidateComponentProvider scanner = getScanner();
        //筛选出远程调用的本地接口
        scanner.setResourceLoader(this.resourceLoader);

        //获取启动注解标注的接口类名数组
        Map<String, Object> attributes = metadata.getAnnotationAttributes(SyyrjxRpcCallEnable.class.getName());
        Class<?>[] callClientsClassesArray = ((Class<?>[])attributes.get("value"));

        Set<Class<?>> callClientClassSet = new HashSet<>();
        if (callClientsClassesArray != null) {
            callClientClassSet.addAll(Arrays.asList(callClientsClassesArray));
        }

        for (Class<?> callClientClass : callClientClassSet) {
            BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(SyyrjxRpcCallClientFactoryBean.class);
            definition.addConstructorArgValue(callClientClass);

            long timeout = 0;
            Class<? extends Exception>[] ignoreExceptions = new Class[0];
            SyyrjxRpcBreaker callClientAnnotation = callClientClass.getAnnotation(SyyrjxRpcBreaker.class);
            if (callClientAnnotation != null) {
                definition.addConstructorArgValue(true);
                timeout = callClientAnnotation.timeout();
                ignoreExceptions = callClientAnnotation.ignoreException();
            }
            definition.addConstructorArgValue(timeout);
            definition.addConstructorArgValue(ignoreExceptions);

            AbstractBeanDefinition handleDefinition = definition.getBeanDefinition();
            handleDefinition.setPrimary(true);

            BeanDefinitionHolder holder = new BeanDefinitionHolder(handleDefinition, callClientClass.getName());
            BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);

        }

        LOGGER.debug("代理实现类bean注册完毕");
    }

    private ClassPathScanningCandidateComponentProvider getScanner() {
        return new ClassPathScanningCandidateComponentProvider(false, this.environment);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        LOGGER.debug("上下文加载完毕后置处理");
    }
}
